package core;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.Serializable;

import core.reports.ReportData;

/**
 * An implementation of ILoader that uses Java Serialization.  This implementation expects to 
 * receive a location of a file on disk, preferably created by SerializableSaver.
 * @author Royce
 *
 */
public class SerializableLoader implements ILoader, Serializable {
	
	private static final long serialVersionUID = 5347425386348589239L;
	/**
	 * The ObjectInputStream used to read objects from a given location.
	 */
	private ObjectInputStream inStream;
	
	/**
	 * Default constructor.
	 */
	public SerializableLoader () {
		
	}

	@Override
	/**
	 * @inheritDoc
	 * Loads a Tracker from a file at the given location.
	 * @param location A location of a file on disk.
	 */
	public boolean load() throws IOException, ClassNotFoundException {
		load("tracker.tkr");
		
		return true;
	}
	
	@Override
	public boolean load(String fileName) throws IOException, ClassNotFoundException {
		inStream = new ObjectInputStream(new FileInputStream(fileName));
		RootStorageUnit.setInstance((RootStorageUnit)inStream.readObject());
		ItemManager.setInstance((ItemManager)inStream.readObject());
		ProductManager.setInstance((ProductManager)inStream.readObject());
		ReportData.setInstance((ReportData)inStream.readObject());
		
		return true;
	}

	
	@Override
	public boolean close() {
		try {
			inStream.close();
			return true;
		} catch (IOException e) {
			e.printStackTrace();
			return false;
		}
	}
}
